﻿<template>
  <info-card title="租赁设置" ref="cardRef">
    <el-form ref="rentalFormRef" :model="rentalForm" :rules="formRule" label-width="auto">
      <el-form-item label="租赁对象" prop="rentObjectList">
        <el-checkbox-group v-model="rentalForm.rentObjectList">
          <el-checkbox
            v-for="item in getConfig('qingyun.product.rent.object.type')"
            :key="item.dictValue"
            :value="item.dictValue"
          >
            <template #default>
              <div v-if="item.dictValue === '1'">{{ item.dictLabel }}</div>
              <div class="flex-inline" v-else>
                {{ item.dictLabel }}，价格为个人的
                <el-form-item
                  :prop="rentalForm.priceRatio"
                  :rule="formRule.priceRatio"
                  :style="{ 'margin-left': '10px' }"
                >
                  <el-input-number :controls="false" :min="0" v-model="rentalForm.priceRatio" :align="'left'">
                    <template #suffix> % </template>
                  </el-input-number>
                </el-form-item>
              </div>
            </template>
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="C端渠道" prop="channelType">
        <el-row :gutter="10" class="radio-list">
          <el-col
            :span="8"
            class="radio-list-item"
            v-for="item in getConfig('qingyun.product.channel.type')"
            :key="item.dictValue"
            @click="checkChannel(item.dictValue)"
          >
            <div class="radio-list-item-top">
              <div
                :class="{ 'top-circle': true, 'top-circle-active': item.dictValue === rentalForm.channelType }"
              ></div>
              {{ item.dictLabel }}
            </div>
            <div
              class="radio-list-item-bottom"
              v-if="rentalForm.channelType === '2' && item.dictValue === rentalForm.channelType"
            >
              <el-button class="add-btn" @click="handleOpenChannnel">选择渠道</el-button>
              <base-empty description="暂无数据" v-if="!rentalForm?.channelList.length" />

              <div class="check-list">
                <el-space :size="8" wrap>
                  <el-tag
                    v-for="(channelItem, channelIdx) in rentalForm.channelList"
                    :key="channelIdx"
                    size="large"
                    closable
                    @close="handleDelChannel(channelIdx, channelItem)"
                  >
                    {{ channelItem.miniName }}
                  </el-tag>
                </el-space>
              </div>
            </div>
            <div
              class="radio-list-item-bottom"
              v-if="rentalForm.channelType === '3' && item.dictValue === rentalForm.channelType"
            >
              <el-form-item
                :label-width="150"
                label="芝麻租赁商品类目"
                :prop="rentalForm.zhimaCateory"
                :rules="formRule.zhimaCateory"
              >
                <el-cascader v-model="rentalForm.zhimaCateory" :options="[]" placeholder="请选择类目" />
              </el-form-item>
              <el-form-item
                :label-width="150"
                label="商品详情页样式"
                :prop="rentalForm.zhimaDetailStyle"
                :rules="formRule.zhimaDetailStyle"
              >
                <el-radio-group v-model="rentalForm.zhimaDetailStyle">
                  <el-radio
                    v-for="el in getConfig('qingyun.product.zhima.detail.style')"
                    :key="el.dictValue"
                    :value="el.dictValue"
                  >
                    {{ el.dictLabel }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item
                :label-width="150"
                label="是否已设置自动推广"
                :prop="rentalForm.zhimaAutomatic"
                :rules="formRule.zhimaAutomatic"
              >
                <el-radio-group v-model="rentalForm.zhimaAutomatic">
                  <el-radio
                    v-for="el in getConfig('qingyun.product.zhima.automatic')"
                    :key="el.dictValue"
                    :value="el.dictValue"
                  >
                    {{ el.dictLabel }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item :label-width="150" label="支付宝小程序" :prop="rentalForm.appId" :rules="formRule.appId">
                <el-select v-model="rentalForm.appId" placeholder="请选择支付宝小程序">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="租赁方案" prop="rentPlan">
        <el-row :gutter="10" class="radio-list">
          <el-col
            :span="8"
            class="radio-list-item"
            :style="{ width: '34%' }"
            v-for="item in getConfig('qingyun.product.rent.plan')"
            :key="item.dictValue"
            @click="checkPlan(item.dictValue)"
          >
            <div class="radio-list-item-top">
              <div :class="{ 'top-circle': true, 'top-circle-active': item.dictValue === rentalForm.rentPlan }"></div>
              {{ item.dictLabel }}
            </div>
            <div
              class="radio-list-item-bottom"
              v-if="rentalForm.rentPlan === '2' && item.dictValue === rentalForm.rentPlan"
            >
              <el-button class="add-btn" @click.stop="handleOpenPlan">选择方案</el-button>
              <base-empty description="暂无数据" v-if="!rentalForm.productRentPlanList.length" />
              <div class="check-list">
                <el-space :size="8" wrap>
                  <el-tag
                    v-for="(planItem, planIdx) in rentalForm.productRentPlanList"
                    :key="planIdx"
                    size="large"
                    closable
                    @close="handleDelPlan(planIdx)"
                  >
                    {{ `${planItem.planName}：${planName(planItem.planChannelList)}` }}
                  </el-tag>
                </el-space>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <!-- 渠道选择 -->
    <base-dialog
      v-model="channelAleryShow"
      title="选择渠道"
      width="600"
      :show-footer="true"
      destroy-on-close
      @close="handelHideChannelAlet"
      @cancel="handelHideChannelAlet"
      @confirm="handleChannelAlertConfirm"
    >
      <el-checkbox-group v-model="alertCheckChannel">
        <el-checkbox v-for="item in channelData" :key="item.id" :label="item.miniName" :value="item.id" />
      </el-checkbox-group>
    </base-dialog>
    <!-- 方案选择 -->
    <base-dialog
      v-model="planVisble"
      title="选择方案"
      width="600"
      :show-footer="true"
      destroy-on-close
      @close="handelHidePlan"
      @cancel="handelHidePlan"
      @confirm="handlePlanConfirm"
    >
      <el-form ref="planFormRef" :model="planForm" :rules="planFormRule" label-width="auto">
        <el-form-item label="方案名称" prop="planName">
          <el-input placeholder="请输入方案名称" :maxlength="6" v-model="planForm.planName" />
        </el-form-item>
        <el-form-item label="适用渠道" prop="planChannelList">
          <el-checkbox-group v-model="planForm.planChannelList">
            <el-checkbox
              v-for="item in availableChannelList"
              :key="item.id"
              :label="item.miniName"
              :value="item.id"
              :disabled="planChannelDisabled(item)"
            />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </base-dialog>
  </info-card>
</template>

<script setup>
  import infoCard from "./InfoCard.vue";
  import { useUserInfoStore } from "@/store/modules/userInfo";
  import mittBus from "tools-utils/mitt";
  const userStore = useUserInfoStore();
  const emit = defineEmits(["updatePlan", "resetPlan"]);
  // 卡片Ref
  const cardRef = ref();
  // 详情
  const detail = inject("detail");
  // 获取配置选项
  const getConfig = inject("getConfig");
  // 表单Ref
  const rentalFormRef = ref();
  // 表单
  const rentalForm = ref({
    rentObjectList: [],
    priceRatio: 0,
    channelType: "",
    zhimaCateory: [],
    zhimaDetailStyle: "",
    zhimaAutomatic: "",
    rentPlan: "",
    appId: "",
    channelList: [],
    productRentPlanList: [],
  });
  // 表单规则
  const formRule = reactive({
    rentObjectList: [{ required: true, message: "请选择租赁对象", trigger: "change" }],
    priceRatio: [{ required: false, message: "请输入比例", trigger: "blur" }],
    channelType: [{ required: true, message: "请选择C端渠道", trigger: "change" }],
    zhimaCateory: [{ required: true, message: "请选择芝麻租赁商品类目", trigger: "blur" }],
    zhimaDetailStyle: [{ required: true, message: "请选择商品详情页样式", trigger: "change" }],
    zhimaAutomatic: [{ required: true, message: "请选择是否已设置自动推广", trigger: "change" }],
    rentPlan: [{ required: true, message: "请选择租赁方案", trigger: "change" }],
    appId: [{ required: true, message: "请选择支付宝小程序", trigger: "change" }],
  });
  // 渠道选择弹窗显示
  const channelAleryShow = ref(false);
  // 渠道弹窗选择
  const alertCheckChannel = ref([]);
  // 方案选项显示
  const planVisble = ref(false);
  // 弹窗方案选择Ref
  const planFormRef = ref();
  // 方案选择Form
  const planForm = ref({
    planName: "",
    planChannelList: [],
  });
  // 方案rule
  const planFormRule = reactive({
    planName: [{ required: true, message: "请输入方案名称", trigger: "blur" }],
    planChannelList: [{ required: true, message: "请选择适用渠道", trigger: "change" }],
  });
  // 渠道数据
  const channelData = ref([]);
  // 可供指定方案选择的渠道
  const availableChannelList = ref([]);
  // 方案名称处理
  const planName = computed(() => {
    return planData => {
      if (planData) {
        const list = planData.map(el => el.miniName);
        return list.join("、");
      }
    };
  });
  // 方案渠道是否可选
  const planChannelDisabled = computed(() => {
    return info => {
      const allCheckChannel = [];
      rentalForm.value.productRentPlanList.forEach(item => {
        allCheckChannel.push(...item.planChannelList);
      });
      const isExist = allCheckChannel.find(el => el.id === info.id);
      if (isExist) {
        return true;
      } else {
        return false;
      }
    };
  });
  watch(detail, val => {
    init();
  });
  // 初始化
  onMounted(() => {
    loadChannelData();
  });
  // 详情初始化
  const init = () => {
    const {
      rentObjectList,
      priceRatio,
      channelType,
      zhimaCateory,
      zhimaDetailStyle,
      zhimaAutomatic,
      rentPlan,
      appId,
      productChannelList,
      productRentPlanList,
    } = detail.value;
    // 设置表单
    rentalForm.value = {
      rentObjectList: rentObjectList.map(el => `${el}`),
      priceRatio: priceRatio ? priceRatio : null,
      channelType: `${channelType}`,
      zhimaCateory: [],
      zhimaDetailStyle: "",
      zhimaAutomatic: "",
      rentPlan: `${rentPlan}`,
      appId: "",
      channelList:
        productChannelList?.map(el => {
          return { id: el.channelCode, miniName: el.channelName };
        }) || [],
      productRentPlanList:
        rentPlan === 2
          ? productRentPlanList?.map(el => {
              const name = el?.productChannelList?.map(item => {
                return { id: item.channelCode, miniName: item.channelName };
              });
              return {
                id: el.id,
                planName: el.planName,
                planChannelList: name,
              };
            })
          : [],
    };
  };
  // 获取渠道数据
  const loadChannelData = () => {
    Api.product.getChannelNew().then(res => {
      channelData.value = res.data.map(el => {
        return { id: el.channelCode, miniName: el.channelName, ...el };
      });
    });
    // Api.product.getChannel({ tenantId: userStore.userInfo.tenantId }).then(res => {
    //   channelData.value = res.data;
    // });
  };
  // 选择方案
  const checkPlan = val => {
    rentalForm.value.rentPlan = val;
    if (val === "2" && rentalForm.value.productRentPlanList.length > 0) {
      mittBus.emit("showMutiple", true);
    } else {
      mittBus.emit("showMutiple", false);
    }
  };
  // 部分渠道-选择渠道
  const checkChannel = val => {
    rentalForm.value.channelType = val;
    // if (val === "1") {
    //   rentalForm.value.channelList = [];
    // }
  };
  // 部分渠道-打开渠道选择弹窗
  const handleOpenChannnel = () => {
    alertCheckChannel.value = rentalForm.value.channelList.map(el => el.id);
    channelAleryShow.value = true;
  };
  // 部分渠道-关闭渠道选择弹窗
  const handelHideChannelAlet = () => {
    channelAleryShow.value = false;
    alertCheckChannel.value = [];
  };
  // 部分渠道-弹窗确认渠道选择
  const handleChannelAlertConfirm = () => {
    if (!alertCheckChannel.value.length) {
      $msg.warning("请选择渠道");
      return;
    }
    channelAleryShow.value = false;
    rentalForm.value.channelList = alertCheckChannel.value.map(item => {
      const current = channelData.value.find(el => el.id === item);
      return current;
    });
  };
  // 部分渠道-删除渠道
  const handleDelChannel = (idx, info) => {
    rentalForm.value.channelList.splice(idx, 1);
    if (rentalForm.value?.productRentPlanList?.length) {
      console.warn(info, rentalForm.value.productRentPlanList, "9999999999999999999");
      // rentalForm.value.productRentPlanList = rentalForm.value.productRentPlanList.filter(item => {
      //   return item.;
      // });
    }
  };
  // 指定方案-打开方案弹窗
  const handleOpenPlan = () => {
    if (
      (rentalForm.value.channelType === "2" && !rentalForm.value.channelList.length) ||
      !rentalForm.value.channelType
    ) {
      $msg.warning("请选择C端渠道");
      return;
    }
    if (rentalForm.value.channelType === "1") {
      availableChannelList.value = JSON.parse(JSON.stringify(channelData.value));
    }
    if (rentalForm.value.channelType === "2" && rentalForm.value.channelList.length) {
      availableChannelList.value = JSON.parse(JSON.stringify(rentalForm.value.channelList));
    }
    planVisble.value = true;
  };
  // 指定方案-关闭方案弹窗
  const handelHidePlan = () => {
    planVisble.value = false;
  };
  // 指定方案-方案确认选择
  const handlePlanConfirm = () => {
    planFormRef.value.validate(ok => {
      if (ok) {
        const exist = rentalForm.value.productRentPlanList.find(el => el.planName === planForm.value.planName);
        if (exist) {
          $msg.warning("方案名已存在");
          return;
        }
        const planChannelList = planForm.value.planChannelList.map(item => {
          const current = channelData.value.find(el => el.id === item);
          return current;
        });
        const planData = {
          ...planForm.value,
          id: new Date().getTime(),
          planChannelList: planChannelList,
        };
        rentalForm.value.productRentPlanList.push(planData);
        mittBus.emit("updatePlan", { newPlan: planData, type: "add", delIdx: null });
        planVisble.value = false;
        planForm.value = {
          planName: "",
          planChannelList: [],
        };
        return;
      }
    });
  };
  // 指定方案-删除方案
  const handleDelPlan = idx => {
    if (rentalForm.value.productRentPlanList.length > 1) {
      rentalForm.value.productRentPlanList.splice(idx, 1);
      mittBus.emit("updatePlan", { newPlan: {}, type: "del", delIdx: idx });
      // emit("updatePlan", rentalForm.value.productRentPlanList);
    } else {
      $msg.warning("至少保留一个指定方案");
    }
  };
  // 表单验证
  const formVerify = () => {
    return rentalFormRef.value.validate();
  };
  const getTop = () => {
    return cardRef.value.getTop();
  };
  // 暴露方法
  defineExpose({
    formVerify,
    getTop,
    rentalForm,
  });
</script>

<style lang="scss" scoped>
  .flex-inline {
    display: flex;
    align-items: center;
  }
  .radio-item {
    width: 330px;
    .radio-item-title {
      width: 100%;
    }
  }
  .radio-item-bottom {
    width: 100%;
    height: 158px;
    border: 1px solid var(--cb1);
  }
  .radio-list {
    width: 100%;
    display: flex;
    // flex-wrap: wrap;

    .radio-list-item {
      .radio-list-item-top {
        display: flex;
        align-items: center;
        width: 100%;

        .top-circle {
          width: 14px;
          height: 14px;
          border: 1px solid var(--cb1);
          border-radius: 50%;
          background-color: var(--fl7);
          margin-right: 8px;
          cursor: pointer;
        }
        .top-circle-active {
          border: 4px solid var(--bd);
        }
      }
      .radio-list-item-bottom {
        // width: 100%;
        min-height: 158px;
        border: 1px solid var(--cb1);
        border-radius: 8px;
        padding: 16px;
        margin-top: 8px;
        .add-btn {
          border: 1px solid var(--bd3);
          color: var(--bd3);
        }
        .check-list {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          margin-top: 10px;
          .check-item {
            padding: 0 12px;
            font-size: 14px;
            color: var(--ct2);
            background-color: var(--fl1);
            border-radius: 4px;
          }
        }
      }
    }
  }
  .radio-list-flex {
    justify-content: space-between;
  }
</style>
